﻿
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace Loogn.DataMeta
{
    public class Meta
    {
        public Meta() { }
        public Meta(string connStr)
        {
            this.ConnectionString = connStr;
        }
        public string ConnectionString { get; set; }

        public List<TableInfo> GetTables()
        {
            using (var reader = SqlHelper.ExecuteReader(ConnectionString, System.Data.CommandType.Text, Sql.GetTablesSql))
            {
                List<TableInfo> list = new List<TableInfo>();
                while (reader.Read())
                {
                    list.Add(new TableInfo
                    {
                        Name = reader["Name"].ToString(),
                        Description = reader["Description"].ToString()
                    });
                }
                return list;
            }
        }


        public List<TableInfo> GetTablesWithColumns()
        {
            var list = GetTables();
            foreach (var table in list)
            {
                table.Columns = GetColumns(table.Name);
            }
            return list;
        }



        public List<ColumnInfo> GetColumns(string tableName)
        {
            using (var reader = SqlHelper.ExecuteReader(ConnectionString, System.Data.CommandType.Text, Sql.GetColumnsSql, new SqlParameter("@tableName", tableName)))
            {
                List<ColumnInfo> list = new List<ColumnInfo>();
                while (reader.Read())
                {
                    list.Add(new ColumnInfo
                    {
                        DefaultValue = reader["DefaultValue"].ToString(),
                        Name = reader["Name"].ToString(),
                        Description = reader["Description"].ToString(),
                        IsIdentity = reader["IsIdentity"].Equals(1),
                        IsNullable = reader["IsNullable"].Equals(1),
                        IsPrimaryKey = reader["IsPrimaryKey"].Equals(1),
                        Length = (int)reader["Length"],
                        SqlDataType = reader["SqlDataType"].ToString()
                    });
                }
                return list;
            }
        }
    }
}
